package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.activity.TestActivity;
import com.luoxiang.socialandroid.activity.VedioActivity;
import com.luoxiang.socialandroid.adapter.FriendAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.BeforeCallBean;
import com.luoxiang.socialandroid.bean.Friend;
import com.luoxiang.socialandroid.bean.FriendsBean;
import com.luoxiang.socialandroid.bean.GetMessageBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class FriendFollowFragment extends LazyLoadFragment {
    private RecyclerView rc_ff;
    private String token, mUserid;
    private FriendAdapter adapter;
    private int page = 1;//是我们的页数
    private SmartRefreshLayout smartRefreshLayout;
    private ArrayList<Friend> list;
    private ImageView img_noshuju;
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private TextView tv_noshuju;

    @Override
    protected int setContentView() {
        return R.layout.fragment_fans;
    }

    @Override
    protected void initView() {
        mUserid = MmkvUtil.INSTANCE.decodeString(ACCID);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        rc_ff = findViewById(R.id.rc_fans);
        tv_noshuju = findViewById(R.id.tv_noshuju);
        list = new ArrayList<>();
        smartRefreshLayout = findViewById(R.id.smartRefresh);
        img_noshuju = findViewById(R.id.img_noshuju);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rc_ff.setLayoutManager(linearLayoutManager);
        adapter = new FriendAdapter();
        rc_ff.setAdapter(adapter);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getFriendFollow(token, EXTRA, "0", page, 10);
            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getFriendFollow(token, EXTRA, "0", page, 10);
            }
        });

    }

    @Override
    protected void lazyLoad() {
        showLoading();
        getFriendFollow(token, EXTRA, "0", page, 10);
    }

    private void getFriendFollow(String token, String extra, String s, int i, int i1) {
        LogUtils.i("token", token);
        NetUtils2.getInstance().getApiService().getUserFriends(token, extra, "0", i, i1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr", decryptStr);
                            Gson gson = new Gson();
                            FriendsBean bean = gson.fromJson(decryptStr, FriendsBean.class);
                            if (bean != null) {
                                if (page == 1) {
                                    list.clear();
                                }
                            }
                            if (bean.getData() != null && bean.getData().getFriends() != null && bean.getData().getFriends().size() > 0) {
                                if (list != null) {
                                    list.addAll(bean.getData().getFriends());
                                }
                                img_noshuju.setVisibility(View.GONE);
                                tv_noshuju.setVisibility(View.GONE);
                                adapter.setData(list);
                                adapter.notifyDataSetChanged();
                            } else {
                            }
                            if (bean.getData() != null && bean.getData().getFriends().size() == 0 && page == 1) {
                                img_noshuju.setVisibility(View.VISIBLE);
                                tv_noshuju.setVisibility(View.VISIBLE);
                            }

                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getFriends() != null && bean.getData().getFriends().size() != 0) {

                                        adapter.setOnAddClickListener(new FriendAdapter.OnAddClickListener() {
                                            @Override
                                            public void onItemClicks(int userid) {
                                                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                                intent.putExtra("userid", userid);
                                                startActivity(intent);
                                            }
                                        });
                                        adapter.setOnAddClickListenerDs(new FriendAdapter.OnAddClickListenerDs() {
                                            @Override
                                            public void onItemClicksDs(int userid) {
                                                sayhello(token, EXTRA, userid);
                                            }
                                        });
                                        adapter.setOnAddClickListenerSx(new FriendAdapter.OnAddClickListenerSx() {
                                            @Override
                                            public void onItemClicksSx(int userid) {
                                                if (mUserid.equals(String.valueOf(userid))) {
                                                    ToastUtils.showShort(R.string.mi_bunenghezijiliaotian);
                                                } else {
                                                    XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo(userid + "", "aaa", "")).withContext(getActivity()).navigate();
                                                }
                                            }
                                        });
                                        adapter.setOnAddClickListenerSp(new FriendAdapter.OnAddClickListenerSp() {
                                            @Override
                                            public void onItemClicksSp(int userid) {
                                                //点击视频
                                                getimPre(EXTRA, userid + "", token);
                                            }
                                        });
                                    }
                                }
                            }

                        } catch (Exception e) {
                            LogUtils.e("errorfriend", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });
    }

    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        OurinfoBean bean = gson.fromJson(decryptStr, OurinfoBean.class);
                        TestActivity.ourinfoBean = bean;
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = com.luoxiang.lib_common.utils.MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-", "");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", toUserId + "", null, null, id);
                            CallKitUI.startSingleCall(getContext(), param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void sayhello(String token, String extra, int userid) {
        getRequest();
        NetUtils2.getInstance().getApiService().sayHello(token, extra, userid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStrdazhaohu", decryptStr);
                        Gson gson = new Gson();
                        GetMessageBean getMessageBean = gson.fromJson(decryptStr, GetMessageBean.class);
                        if (getMessageBean.getCode() == 0) {
                        } else {
                            ToastUtils.showShort(getMessageBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }
}
